<template lang="pug">
  div(id="examingDialog" v-if="dialogVisible")
    el-dialog(v-bind:visible.sync="dialogVisible"
    v-bind:fullscreen="true"
    v-bind:show-close="false"
    v-bind:close-on-click-modal="false"
    v-bind:close-on-press-escape="false"
    custom-class="exam-dialog"
    ref="examingDialog")
      el-container.exam-dialog--container
        el-header.exam-dialog--header
          div.col.title
            div.lable 考试科目：
            div.cnt {{examData.kskm}}
          div.col.timer(v-if="examState===2 && (totalS > 0)")
            div.lable 距离考试结束还有：
            div.cnt {{timer.hh}} 小时 {{timer.mm}} 分 {{timer.ss}} 秒
          div.col.timer(v-else-if="examState===4")
            div.lable 时间到：
            div.cnt 考试结束
          div.col.timer(v-else)
            div.lable 考试时间：
            div.cnt {{totalMinute}} 分钟
          div.col.student
            div.lable 当前考生：
            div.cnt {{currentStu}}
        el-main.exam-dialog--main
          div.exam-loading(v-if="examState===0")
            div.exam-loading--icon
              i.el-icon-loading()
            div.exam-loading--text 正在加载试题，请稍后……
          div.exam-ready(v-if="examState===1")
            div.title 试卷加载完成
            el-button(v-on:click="handlerClickBtnBeginExam") 开始答卷
          div.exam-paper(v-if="examState===2")
            div.papers-area(v-for="(pItem,i) in papers")
              div.type-name {{pItem.title}}
              div.questions-area(v-for="(qItem,j) in pItem.question")
                div.title
                  span {{j+1}}.
                  | {{qItem.stem}}
                div.options-area(v-if="qItem.paperBean.quesType === '2'")
                  div.options-item--area
                    div.options-item
                      el-radio(v-model="answer[i+':'+j]" label="A") A. {{qItem.answerA}}
                    div.options-item
                      el-radio(v-model="answer[i+':'+j]" label="B") B. {{qItem.answerB}}
                    div.options-item
                      el-radio(v-model="answer[i+':'+j]" label="C") C. {{qItem.answerC}}
                    div.options-item
                      el-radio(v-model="answer[i+':'+j]" label="D") D. {{qItem.answerD}}
                template(v-else-if="qItem.paperBean.quesType === '5'")
                  <!--div.options-item&#45;&#45;area.area-2(v-if="qItem.paperBean.subType === '1'")-->
                  <!--div.answer&#45;&#45;constraint {{qItem.answerConstraint}}-->
                  <!--div.answer&#45;&#45;textarea-->
                  <!--div-->
                  <!--el-input(type="textarea" v-model="answer[i+':'+j]" v-bind:autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入答案")-->
                  div.options-item--area.area-2
                    div.update-txt 上传附件的要求和相关介绍
                    div
                      kalix-upload(v-model="answerPicPath[i+':'+j]" v-bind:isImage="true" style="width:100%")
          div.exam-ready.exam-end(v-if="examState===4")
            div.title 答题时间到！试卷已自动提交。
            div.cnt
              div
                span.close-timer {{closeTimer}}
                | 秒后自动关闭
              div
                | 可以点击
                span.link-close-exam(v-on:click="handlerClickCloseExamDialog") 这里
                | 关闭答卷
        el-footer
          div.footer-mn
          div.btns-area
            el-button(type="success" v-bind:disabled="!showBtnSubmitExam" icon="el-icon-check" round
            v-on:click="handlerClickBtnSubmit"
            ) 交卷

</template>

<script type="text/ecmascript-6">
  import {
    ExamingPaperURL
    , ExamingCommitURL, ExamingCheckTime
  } from '../config.toml'

  export default {
    name: 'examingDialog',
    data() {
      return {
        bizKey: 'examing',
        dialogVisible: false,
        btnSubmitDisabled: false,
        papers: [],
        totalMinute: null,
        totalS: 0,
        timer: {},
        totalSeconde: 0,
        examingTimer: 0,
        targetUrl: ExamingPaperURL,
        answer: {},
        answerPicPath: {},
        examData: {},
        nextQuesNum: 0,
        timerMT: null,
        timeUp: false,
        examState: 0,  // 考试状态 [0:等待加载,1：加载完成，2:正在考试，3:考试完成，4:时间到 ]
        closeExamMT: null,
        closeTimer: 3,
        minSubmitDate: 30, // 分钟
        quesLen: 0, // 总题数
        currentStu: ''
      }
    },
    mounted() {
      this.nextQuesNum = -1
    },
    methods: {
      /**
       * 打开对话框
       */
      open(row) {
        this.dialogVisible = true
        this.currentStu = this.$KalixCatch.get('user_name')
        this.getPaper(row.paperId, row.id)
        this._checkTime()
      },
      _checkTime() {
        this._closeCheckTime()
        this.mtCheckTime =
          this.$http.get(ExamingCheckTime)
            .then(res => {
              if (document.getElementById('examingDialog')) {
                setTimeout(() => {
                  this._checkTime()
                }, 1000 * 60 * 10)
              } else {
                this._closeCheckTime()
              }
            })
      },
      /**
       * 关闭定时请求
       */
      _closeCheckTime() {
        clearTimeout(this.mtCheckTime)
      },
      /**
       * 倒计时
       */
      countDown() {
        clearInterval(this.timerMT)
        this.timerMT = setInterval(() => {
          console.log('this.totalS:', this.totalS)
          this.totalS = this.totalS - 1
          this.examingTimer += 1
          this.timer = this._dateFormat(this.totalS)
          console.log('this.timer:', this.timer)
          if (this.totalS < 0) {
            /**
             * 倒计时结束自动提交试卷
             */
            this._autoSubmitExam()
            clearInterval(this.timerMT)
            console.log('The End')
          }
        }, 1000)
      },
      _dateFormat(second) {
        let dd, hh, mm, ss
        second = typeof second === 'string' ? parseInt(second) : second
        if (second < 0) {
          return
        }
        // 天
        dd = second / (24 * 3600) | 0
        second = Math.round(second) - dd * 24 * 3600
        // 小时
        hh = second / 3600 | 0
        second = Math.round(second) - hh * 3600
        // 分
        mm = second / 60 | 0
        // 秒
        ss = Math.round(second) - mm * 60
        if (Math.round(dd) < 10) {
          dd = dd > 0 ? '0' + dd : ''
        }
        // if (Math.round(hh) < 10) {
        //   hh = '0' + hh
        // }
        if (Math.round(mm) < 10) {
          mm = '0' + mm
        }
        if (Math.round(ss) < 10) {
          ss = '0' + ss
        }
        return {
          dd,
          hh,
          mm,
          ss
        }
      },
      /**
       * 关闭对话框
       */
      _closeDialog() {
        this.dialogVisible = false
        this._closeCheckTime()
        this.$KalixEventBus.$emit(this.bizKey + '-' + 'KalixDialogClose', null)
      },
      /**
       * 关闭对话框按钮点击事件
       */
      handlerClickBtnCloseDialog() {
        this._closeDialog()
      },
      /**
       * 交卷
       */
      handlerClickBtnSubmit() {
        // clearInterval(this.timerMT)
        this.$confirm('确认交卷', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this._submitExam(() => {
            this._closeDialog()
          })
        }).catch(() => {
          this.countDown()
        })
      },
      /**
       * 开始答卷
       */
      handlerClickBtnBeginExam() {
        this.examState = 2
        this.totalS = this.totalMinute * 60
        // this._dateFormat()
        this.countDown()
      },
      /**
       * 生成试卷
       */
      getPaper(paperId, examId) {
        if (paperId && examId) {
          this.$http.get(this.targetUrl, {
            params: {
              paperId: paperId,
              examId: examId
            }
          }).then(res => {
            console.log('res===============', res.data)
            this.examData = res.data
            this.papers = res.data.quesList
            this.examState = 1
            this.totalMinute = this.examData.duration
            this.minSubmitDate = this.examData.examMinTime
            this.papers.forEach(e => {
              this.quesLen += e.question.length
            })
          })
        }
      },
      /**
       * 关闭考试界面
       * @private
       */
      handlerClickCloseExamDialog() {
        clearInterval(this.closeExamMT)
        this._submitExam()
        this._closeDialog()
        this._exitFullscreen()
      },
      /**
       * 自动提交试卷
       * @private
       * @callback
       */
      _autoSubmitExam() {
        this.examState = 4
        this._tm(() => {
          this.handlerClickCloseExamDialog()
        })
      },
      /**
       * 提交试卷
       * @private
       * @callback
       */
      _submitExam(callBack) {
        let quesList = []
        console.group('提交试卷')
        console.log(`this.answer:`, this.answer)
        for (let k in this.answer) {
          let ij = k.split(':')
          let i = ij[0]
          let j = ij[1]
          let quesObj = this.papers[i]
          let questionObj = quesObj.question[j]
          let paperBean = questionObj.paperBean
          let answer = this.answer[k]
          let answerPicPath = this.answerPicPath[k]
          console.log(`answer${k}:`, answer)
          if (answer === '') {
          }
          quesList.push({
            title: questionObj.stem,
            titleNum: quesObj.titleNum,
            perScore: quesObj.perScore,
            quesid: paperBean.quesid,
            quesNum: j * 1,
            quesType: paperBean.quesType,
            subType: paperBean.subType,
            answer: answer,
            answerPicPath: answerPicPath
          })
        }
        for (let k in this.answerPicPath) {
          let ij = k.split(':')
          let i = ij[0]
          let j = ij[1]
          let quesObj = this.papers[i]
          let questionObj = quesObj.question[j]
          let paperBean = questionObj.paperBean
          let answer = this.answer[k]
          let answerPicPath = this.answerPicPath[k]
          console.log(`answer${k}:`, answer)
          if (answer === '') {
          }
          quesList.push({
            title: questionObj.stem,
            titleNum: quesObj.titleNum,
            perScore: quesObj.perScore,
            quesid: paperBean.quesid,
            quesNum: j * 1,
            quesType: paperBean.quesType,
            subType: paperBean.subType,
            answer: answer,
            answerPicPath: answerPicPath
          })
        }
        console.log(`this.quesLen:`, this.quesLen)
        console.log(`quesList.length:`, quesList.length)
        if (this.quesLen !== quesList.length) {
          this.$alert('必须答完全部试题！', '标题名称', {
            confirmButtonText: '确定'
          })
        }
        console.log('this.quesLen:', this.quesLen)
        console.log('this.quesList:', quesList.length)
        let postData = {
          examId: this.examData.examId,
          paperId: this.examData.paperId,
          quesList
        }
        console.log('POST DATA:', postData)
        console.groupEnd()
        /*
        */
        this.$http.post(ExamingCommitURL, postData).then(res => {
          if (res.data.success) {
            callBack()
          } else {
            this.$KalixMessage.error(res.data.msg)
          }
        }).catch(err => {
          console.error('err', err)
        })
      },
      _setPostDataQuesList() {
        return []
      },
      /**
       * 退出全屏
       * @private
       */
      _exitFullscreen() {
        if (document.exitFullscreen) {
          document.exitFullscreen()
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen()
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else if (document.webkitCancelFullScreen) {
          document.webkitCancelFullScreen()
        }
      },
      _tm(callBack) {
        clearInterval(this.closeExamMT)
        this.closeExamMT = setInterval(() => {
          this._dateFormat(this.closeTimer)
          this.closeTimer -= 1
          console.log('this.closeTimer:', this.closeTimer)
          if (this.closeTimer < 1) {
            clearInterval(this.closeExamMT)
            if (typeof (callBack) === 'function') {
              callBack()
            }
          }
        }, 1000)
      }
    },
    computed: {
      showBtnSubmitExam() {
        return this.examingTimer > (this.minSubmitDate * 60) && this.examState === 2
      }
    },
    watch: {}
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  .exam-paper
    .papers-area
      & + .papers-area
        margin-top 50px
      .type-name
        font-size 16px
      .questions-area
        margin-top 20px
        .title
          font-size 16px
          margin-bottom 5px
          padding-left 24px
          span
            margin-right 8px
        .options-area
          padding 24px
          position relative
          overflow hidden
          &:after
            position absolute
            display block
            content ''
            height 1px
            left 0
            right 0
            bottom 0
            background-color #cccccc
          .options-item--area
            float left
            clear both
            &.area-2
              width 100%
          .options-item
            font-size 14px
            margin-top 10px
            display flex
            cursor pointer
            .tag
              font-weight bold
              margin-right 8px
            .text
              flex 1

          .answer--constraint
            line-height 1.5
            margin-bottom 20px
          .answer--textarea
            width 50%

      .update-txt
        padding 10px 24px
        font-size 16px

  .exam-loading,
  .exam-ready
    width 100%
    height 100%
    position relative
    display flex
    align-items center
    justify-content center
    flex-direction column
    color #409EFF

  .exam-loading
    .exam-loading--icon
      font-size 64px
    .exam-loading--text
      font-size 20px
      margin-top 24px

  .exam-ready
    .title
      font-size 32px
      margin-bottom 20px

  .exam-end
    color #000000
    .title
      font-size 32px
    .cnt
      font-size 20px
      line-height 1.5
      text-align center
      color #555555
      margin 30px
      .close-timer
        font-size 30px
        cursor pointer
        margin-right 8px
        color #409eff
      .link-close-exam
        margin 0 4px
        font-weight bold
        color #409eff
        cursor pointer
        position relative
</style>
